package com.accp.controller;

import javax.management.RuntimeErrorException;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.accp.common.DataResult;
import com.accp.entity.Hotevents;
import com.accp.entity.Users;
import com.accp.service.HoteventsService;
import com.baomidou.mybatisplus.core.metadata.IPage;

import io.swagger.annotations.Api;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jack
 * @since 2021-08-03
 */
@RestController
@RequestMapping("/hotevents")
@Api(tags = "热门事件接口")
public class HoteventsController {
	
	@Autowired
	HoteventsService eventService;

	// 分页查询
	@GetMapping("/page")
	public DataResult getEventByPage(
			@RequestParam(required=false,defaultValue="1") int pageIndex, 
			@RequestParam(required=false,defaultValue="3") int pageRows, 
			@RequestParam(required=false,defaultValue="") String keyword,
			HttpSession session) {
		IPage<Hotevents> ipage = this.eventService.getEventByPage(pageIndex, pageRows, keyword);
		Users user = (Users)session.getAttribute("user");
		if(user != null){
			//循环去控制每个事件的可编辑状态
			for(Hotevents event : ipage.getRecords()){
				if(user.getId() == event.getUid()){
					event.setCanEdit(true);
				}
				if(user.getLevel() == 1){
					event.setCanEdit(true);
				}
			}
		}
		return DataResult.getSuccessResult(ipage);
	}

	// 查询事件详情
	@GetMapping("/fetch")
	public DataResult fetchEvent(int id) {
		Hotevents event = this.eventService.fetchEvent(id);
		return DataResult.getSuccessResult(event);
	}
	
	@PostMapping("/add")
	public DataResult addEvent(Hotevents event,HttpSession session){
		Users user = (Users) session.getAttribute("user");
		if(user == null){
			throw new RuntimeException("还没有登录");
		}
		event.setUid(user.getId());
		int result = this.eventService.addEvent(event);
		if(result == 1){
			return DataResult.getSuccessResult(result);
		}else{
			return DataResult.getErrorResult(401, result, "添加失败");
		}
	}
	
	@PostMapping("/update")
	public DataResult updateEvent(Hotevents event,HttpSession session){
		Users user = (Users)session.getAttribute("user");
		if(user == null){
			throw new RuntimeException("还没有登录");
		}
		//level=0是普通用户
		if(user.getLevel() == 0){
			if(user.getId() != event.getUid()){
				throw new RuntimeException("没有权限编辑该事件");
			}
		}
		//验证当前用户是否有权限编辑
		
		int result = this.eventService.updateEvent(event);
		if(result == 1){
			return DataResult.getSuccessResult(result);
		}else{
			return DataResult.getErrorResult(401, result, "更新失败");
		}
	}
}
